home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 3: Developer Tools / Linux Cubed Series 3 - Developer Tools.iso / devel / lang / c / pthd-0.000 / pthd-0 / pthd-0.7 / src_mutex / mutex.c < prev   
Encoding:
C/C++ Source or Header  |  1995-08-16  |  1.9 KB  |  90 lines

  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <pthread.h>
  4. #include "utils.h"
  5.  
  6. void lock_mu( pthread_mutex_t *mu )
  7. {
  8.    int st;
  9.  
  10.    printf_r("Child attempting to lock mutex\n");
  11.    st = pthread_mutex_lock( mu );
  12.    CHECK(st, "pthread_mutex_lock()");
  13.    printf_r("... mutex locked\n");
  14.  
  15.    st = pthread_mutex_unlock( mu );
  16.    CHECK(st, "pthread_mutex_unlock()");
  17.    printf_r("... mutex unlocked\n");
  18.  
  19.    pthread_exit( (void *) SUCCESS );
  20. }
  21.  
  22. void
  23. init_mu( pthread_mutex_t *mu )
  24. {
  25.    int st;
  26.  
  27.    st = pthread_mutex_init( mu, NULL );
  28.    CHECK( st, "pthread_mutex_init()");
  29. }
  30.  
  31. void
  32. destroy_mu( pthread_mutex_t *mu )
  33. {
  34.    int st;
  35.  
  36.    st = pthread_mutex_destroy( mu );
  37.    CHECK(st, "pthread_mutex_destroy()");
  38. }
  39.  
  40. static pthread_mutex_t mutex;
  41. static pthread_t th;
  42.  
  43. int 
  44. main( int argc, char *argv[] )
  45. {
  46.    int st, exit_status;
  47.    pthread_attr_t th_attr;
  48.  
  49.    init_mu( &mutex );
  50.  
  51.    /*
  52.     *  --  Set the child's thread attributes so that the main() thread
  53.     *      can join it.
  54.     */
  55.    (void) pthread_attr_init( &th_attr );
  56.    (void) pthread_attr_setdetachstate( &th_attr, PTHREAD_CREATE_JOINABLE );
  57.  
  58.    /*
  59.     *  --  Now, lock the mutex, and create the child thread.  The child
  60.     *      will attempt to lock the same mutex, and block until
  61.     *      the mutex is released.
  62.     */
  63.    st = pthread_mutex_lock( &mutex );
  64.    CHECK(st, "pthread_mutex_lock()");
  65.    printf_r("Main has locked the mutex\n");
  66.  
  67.    /*
  68.     *  --  This is the second thread that should block when it attempts to
  69.     *      lock mu.
  70.     */
  71.    st = pthread_create( &th, &th_attr, (thread_proc_t)lock_mu, &mutex );
  72.    CHECK(st, "pthread_create()");
  73.  
  74.    /*
  75.     *  --  Unlock the mutex
  76.     */
  77.    st = pthread_mutex_unlock( &mutex );
  78.    CHECK(st, "pthread_mutex_unlock()");
  79.    printf_r("Main has unlocked the mutex\n");
  80.  
  81.    st = pthread_join( th, (void **) &exit_status );
  82.    CHECK(st, "pthread_join()");
  83.  
  84.    if( exit_status != SUCCESS )
  85.        printf_r("Failed to join\n");
  86.  
  87.    destroy_mu( &mutex );
  88.    return( EXIT_SUCCESS );
  89. }
  90.